import requests
from bs4 import BeautifulSoup
import re
import traceback

def getHTMLText(url,code='utf-8'):
	try:
		print(url)
		kv = {'user-agent':'Mozila/5.0'}
		r = requests.get(url,headers=kv,timeout=30)
		r.raise_for_status()
		# r.encoding = r.apparent_encoding
		r.encoding = code
		return r.text
	except Exception as e:
		print("访问URL失败")
		return ""

def getStockList(lst,stockUrl):
	html = getHTMLText(stockUrl,'GB2312')	
	soup = BeautifulSoup(html,'html.parser')
	a = soup.find_all('a')
	for i in a:
		try:
			href = i.attrs['href']
			res = re.findall(r"[s][hz]\d{6}",href)
			if (not res == None) and len(res) > 0:
				lst.append(res[0])
		except Exception as e:
			print(e,"访问股票URL失败")
			continue


def getStockInfo(lst,stockUrl,fpath):
	count = 0
	for i in lst:
		url = stockUrl + str(i) +".html"
		html = getHTMLText(url)
		try:
			if html == "":
				continue

			infoDict = {}
			soup = BeautifulSoup(html,'html.parser')
			stockInfo = soup.find('div',attrs={'class':'stock-bets'})
			
			name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
			
			print(name)
			print(name.text)  # 输出所有子节点的内容
			print(name.string) # string 如果有多个子节点，无法确定是哪个内容，所以会返回空
			infoDict.update({'股票名称':name.text.split()[0]})

			keyList =stockInfo.find_all('dt')
			valueList = stockInfo.find_all('dd')
			for i in range(len(keyList)):
				key = keyList[i].text
				val = valueList[i].text
				infoDict[key] = val

			with open(fpath,'a+',encoding='utf-8') as f:
				f.write(str(infoDict) + '\n')
				count = count + 1
				print('\r 当前速度：{:.2f}% '.format(count*100/len(lst)),end='')
		except:
			print('\r 当前速度：{:.2f}% '.format(count*100/len(lst)),end='')
			traceback.print_exc()
			continue

def main():
	stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
	stock_info_url = 'https://gupiao.baidu.com/stock/'
	output_file = 'E://python_study/spider/baiduStock.txt'
	slist = []
	getStockList(slist,stock_list_url)
	# print(slist)
	getStockInfo(slist,stock_info_url,output_file)

main()